﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OvenParameterForm.Util
{
    public static class BoolArrayConverter
    {
        /// <summary>
        /// 将布尔数组转换为字节（8位）
        /// </summary>
        /// <param name="boolArray">布尔数组（长度不超过8）</param>
        /// <param name="msbFirst">指示第一个元素是否代表最高位</param>
        /// <returns>转换后的字节</returns>
        public static byte ToByte(bool[] boolArray, bool msbFirst = false)
        {
            if (boolArray == null)
                throw new ArgumentNullException(nameof(boolArray));
            if (boolArray.Length > 8)
                throw new ArgumentException("布尔数组长度不能超过8位", nameof(boolArray));

            byte result = 0;
            for (int i = 0; i < boolArray.Length; i++)
            {
                int shift = msbFirst ? (7 - i) : i;
                if (boolArray[i])
                    result |= (byte)(1 << shift);
            }
            return result;
        }

        /// <summary>
        /// 将布尔数组转换为32位整数
        /// </summary>
        /// <param name="boolArray">布尔数组（长度不超过32）</param>
        /// <param name="msbFirst">指示第一个元素是否代表最高位</param>
        /// <returns>转换后的32位整数</returns>
        public static int ToInt32(bool[] boolArray, bool msbFirst = false)
        {
            if (boolArray == null)
                throw new ArgumentNullException(nameof(boolArray));
            if (boolArray.Length > 32)
                throw new ArgumentException("布尔数组长度不能超过32位", nameof(boolArray));

            int result = 0;
            for (int i = 0; i < boolArray.Length; i++)
            {
                int shift = msbFirst ? (31 - i) : i;
                if (boolArray[i])
                    result |= 1 << shift;
            }
            return result;
        }

        /// <summary>
        /// 将布尔数组转换为无符号32位整数
        /// </summary>
        /// <param name="boolArray">布尔数组（长度不超过32）</param>
        /// <param name="msbFirst">指示第一个元素是否代表最高位</param>
        /// <returns>转换后的无符号32位整数</returns>
        public static uint ToUInt32(bool[] boolArray, bool msbFirst = false)
        {
            return (uint)ToInt32(boolArray, msbFirst);
        }
    }
}
